package com.flbill.service.impl;

import com.flbill.common.utils.JwtUtils;
import com.flbill.mapper.AdminMapper;
import com.flbill.mapper.ClassMapper;
import com.flbill.mapper.UserMapper;
import com.flbill.pojo.dto.CategoryDTO;
import com.flbill.pojo.dto.LoginDTO;
import com.flbill.pojo.dto.UserPageQueryDTO;
import com.flbill.pojo.entity.User;
import com.flbill.pojo.vo.*;
import com.flbill.service.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    private final AdminMapper adminMapper;
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final ClassMapper classMapper;
    
    public AdminServiceImpl(AdminMapper adminMapper, UserMapper userMapper, PasswordEncoder passwordEncoder,  ClassMapper classMapper) {
        this.adminMapper = adminMapper;
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.classMapper = classMapper;
    }
    
    @Override
    public AdminVO login(LoginDTO loginDTO) {
        AdminVO adminVO = adminMapper.getByUsername(loginDTO);
        //检查用户是否存在
        if(adminVO == null){
            throw new RuntimeException("用户名错误");
        }
        //检查密码
        if(!passwordEncoder.matches(loginDTO.getPassword(), adminVO.getPassword())){
            throw new RuntimeException("密码错误");
        }
        //生成token
        String token = JwtUtils.generateToken(adminVO.getId(), adminVO.getUsername());
        adminVO.setToken(token);
        return adminVO;
    }

    @Override
    public UserPageVO pageQuery(UserPageQueryDTO userPageQueryDTO) {
        // 计算分页参数
        int offset = (userPageQueryDTO.getPage() - 1) * userPageQueryDTO.getPageSize();
        
        // 查询总记录数
        Long total = userMapper.countUsers(userPageQueryDTO.getUsername());
        
        // 查询数据
        List<User> userList = userMapper.pageQuery(
                userPageQueryDTO.getUsername(), 
                offset, 
                userPageQueryDTO.getPageSize()
        );
        
        // 转换为VO对象
        List<UserVO> userVOList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        for (User user : userList) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            
            // 格式化日期
            if (user.getCreateTime() != null) {
                userVO.setCreateTime(user.getCreateTime().format(formatter));
            }
            
            userVOList.add(userVO);
        }
        
        // 返回结果
        return new UserPageVO(total, userVOList);
    }

    @Transactional
    @Override
    public void deleteUser(Integer id) {
        //首先查看是否有该用户
        User user = userMapper.getUserById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        userMapper.deleteUser(id);
    }
    
    @Transactional
    @Override
    public void updateUserStatus(Integer id, Integer status) {
        // 检查用户是否存在
        User user = userMapper.getUserById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查状态值是否合法
        if (status != 0 && status != 1) {
            throw new RuntimeException("状态值无效，只能为0(禁用)或1(启用)");
        }
        
        // 更新用户状态
        userMapper.updateStatus(id, status);
    }

    @Override
    public List<ClassVO> getCategory(String type) {
        List<ClassVO> list = null;
        // 如果type参数为"expense"，则调用classMapper的listExpense方法，返回expense列表
        if(type.equals("expense")){
            list = classMapper.listExpense();
            // 如果type参数为"income"，则调用classMapper的listIncome方法，返回income列表
        } else if (type.equals("income")){
            list = classMapper.listIncome();
            // 返回列表
        } else {
            throw new RuntimeException("分类类型无效，只能为expense或income");
        }
        return list;
    }
    
    @Transactional
    @Override
    public void addCategory(CategoryDTO categoryDTO) {
        // 检查参数
        if (categoryDTO.getClass_name() == null || categoryDTO.getClass_name().isEmpty()) {
            throw new RuntimeException("分类名称不能为空");
        }
        
        // 根据类型添加分类
        String type = categoryDTO.getType();
        if ("expense".equals(type)) {
            classMapper.addExpenseClass(categoryDTO.getClass_name());
        } else if ("income".equals(type)) {
            classMapper.addIncomeClass(categoryDTO.getClass_name());
        } else {
            throw new RuntimeException("分类类型无效，只能为expense或income");
        }
    }
    
    @Transactional
    @Override
    public void updateCategory(Integer id, CategoryDTO categoryDTO) {
        // 检查参数
        if (categoryDTO.getClass_name() == null || categoryDTO.getClass_name().isEmpty()) {
            throw new RuntimeException("分类名称不能为空");
        }
        
        // 检查分类是否存在
        String type = categoryDTO.getType();
        ClassVO classVO = null;
        if ("expense".equals(type)) {
            classVO = classMapper.getExpenseClassById(id);
            if (classVO == null) {
                throw new RuntimeException("支出分类不存在");
            }
            classMapper.updateExpenseClass(id, categoryDTO.getClass_name());
        } else if ("income".equals(type)) {
            classVO = classMapper.getIncomeClassById(id);
            if (classVO == null) {
                throw new RuntimeException("收入分类不存在");
            }
            classMapper.updateIncomeClass(id, categoryDTO.getClass_name());
        } else {
            throw new RuntimeException("分类类型无效，只能为expense或income");
        }
    }
    
    @Transactional
    @Override
    public void deleteCategory(Integer id, String type) {
        // 检查分类是否存在
        ClassVO classVO = null;
        if ("expense".equals(type)) {
            classVO = classMapper.getExpenseClassById(id);
            if (classVO == null) {
                throw new RuntimeException("支出分类不存在");
            }
            classMapper.deleteExpenseClass(id);
        } else if ("income".equals(type)) {
            classVO = classMapper.getIncomeClassById(id);
            if (classVO == null) {
                throw new RuntimeException("收入分类不存在");
            }
            classMapper.deleteIncomeClass(id);
        } else {
            throw new RuntimeException("分类类型无效，只能为expense或income");
        }
    }
}
